package com.szsh.aiot.hsm.runner;

import com.szsh.aiot.framework.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;

@Component
public class InitRunner implements ApplicationRunner {
    private static final Logger LOGGER = LoggerFactory.getLogger(InitRunner.class);

    /*{'289a1c91357a44f2851b481acc68fbde-1.0':'
    {\"appId\":\"289a1c91357a44f2851b481acc68fbde\",\"version\":\"1.0\",\"signatureSecret\":\"uS4EbP9nZ6\",\"encryptMethodType\":1,\"key\":\"CcFOSZeWVmPw+EHALSlDqg==\"}'}
     */
    @Value("#{${app-key}}")
    private Map<String, String> appKeyMap;

    //    private final StringRedisTemplate stringRedisTemplate;

    private final HashOperations<String, String, String> stringHashOperations;

    public InitRunner(StringRedisTemplate stringRedisTemplate) {
//        this.stringRedisTemplate = stringRedisTemplate;
        this.stringHashOperations = stringRedisTemplate.opsForHash();
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("加载密钥.开始");

            LOGGER.info("{}", appKeyMap);
        }

        Iterator<Map.Entry<String, String>> iterator = appKeyMap.entrySet().iterator();
        Map.Entry<String, String> entry;
        while (iterator.hasNext()) {
            entry = iterator.next();
            String[] strArr = entry.getKey().split("-");
            String value = entry.getValue();

            stringHashOperations.putIfAbsent(Constants.REDIS_KEY_PREFIX + strArr[0], strArr[1], value);
        }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("加载密钥.结束");
        }
    }
}
